package com.kfm.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;

public class ConnectionPool {

    private LinkedList<Connection> list = new LinkedList();

    // 连接池中连接的数量
    public int count = 8;

    private String url;
    private String user;

    private String pass;

    public ConnectionPool(String driver, String url, String user, String pass){
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        this.url = url;
        this.user = user;
        this.pass = pass;

        for (int i = 0; i < count; i ++){
            try {
                list.add(createConnection());
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    private Connection createConnection() throws SQLException {
        // 被代理
        Connection connection = DriverManager.getConnection(url, user, pass);

        Connection proxy = (Connection) Proxy.newProxyInstance(ConnectionPool.class.getClassLoader(),
                new Class[]{Connection.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if ("close".equals(method.getName())){
                            // 重新把连接放回池中
//                            System.out.println("放回连接池");
                            return list.add(connection);
                        } else {
                            // 执行操作
                            return method.invoke(connection, args);
                        }
                    }
                });
        return proxy;
    }


    public Connection getConnection(){
        if (list.size() > 0){
            return list.removeLast();
        } else {
            Connection connection = null;
            try {
                connection = createConnection();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            list.add(connection);
            return connection;
        }
    }
}
